package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 网关过滤器
 * @Date 2021/4/5 19:36
 */
@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    /***
     * pre:操作之前执行
     * post：操作之后执行
     * Param: []
     **/
    @Override
    public String filterType() {
        return "pre";
    }

    /***
     * 多个执行顺序。数字越小优先级越高
     * Param: []
     **/
    @Override
    public int filterOrder() {
        return 0;
    }

    /***
     * 当前过滤器是否开启
     * Param: []
     **/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /***
     * 过滤器内执行的操作
     * return 任何值都表示放行
     * setSendZuulResponse(false) 表示不再继续执行
     * Param: []
     **/
    @Override
    public Object run() throws ZuulException {
        System.out.println("经过后台过滤器了。");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        if (request.getMethod().equals("OPTIONS")) {
            return null;
        }

        if(request.getRequestURI().indexOf("/login")>0){
            return null;
        }
        String header = request.getHeader("Authorization");
        if (null != header && !"".equals(header)) {
            if (header.startsWith("Bearer ")) {
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    //如果是admin
                    if (roles.equals("admin")) {
                        //转发头信息
                        requestContext.addZuulRequestHeader("Authorization ", header);
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //终止运行过滤
                    requestContext.setSendZuulResponse(false);
                }
            }
        }
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(403);
        requestContext.setResponseBody("权限不足");
        requestContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
